package org.example.backend.controller;

import org.springframework.jdbc.core.JdbcTemplate;
import org.example.backend.entity.NewsItem;
import org.example.backend.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/news")
@CrossOrigin(origins = "*")
public class NewsController {

    @Autowired
    private NewsService newsService;

    @Autowired(required = false)
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/search")
    public ResponseEntity<?> searchNews(
            @RequestParam String keyword,
            @RequestParam String startDate,
            @RequestParam String endDate) {
        List<NewsItem> results = newsService.searchNews(keyword, startDate, endDate);
        return ResponseEntity.ok(results);
    }

    /**
     * 获取相关新闻（根据政策ID或标题）
     * @param policyId 政策ID（可选）
     * @param title 政策标题（可选）
     * @param size 返回新闻条数，默认5
     */
    @GetMapping("/related")
    public ResponseEntity<?> getRelatedNews(
            @RequestParam(required = false) String policyId,
            @RequestParam(required = false) String title,
            @RequestParam(defaultValue = "5") int size) {
        String keyword = title;
        if (policyId != null && jdbcTemplate != null) {
            try {
                keyword = jdbcTemplate.queryForObject(
                        "SELECT title FROM policy_info WHERE id = ?", String.class, policyId);
            } catch (Exception e) {
                // 查询失败，降级为title
            }
        }
        if (keyword == null || keyword.isEmpty()) {
            return ResponseEntity.badRequest().body("需提供policyId或title");
        }
        // 这里改为调用 searchRelatedNews
        List<NewsItem> results = newsService.searchRelatedNews(keyword, size);
        return ResponseEntity.ok(results);
    }
}

